package common

import (
	"api/common/logger"
	"api/common/orm"
	"api/models"
	"time"
)

// 日志队列
var LoggerQueue = make(chan models.Record, 1000)

// 日志队列入库
func LoggerQueueToDb() {
	defer PanicHandler()
	loggers := make([]models.Record, 0)
	lastTime := time.Now()
	i := 0
	for {
		select {
		case log := <-LoggerQueue:
			loggers = append(loggers, log)
			i += 1
			if i == 1000 {
				LoggerToDb(loggers)
				i = 0
				lastTime = time.Now()
				loggers = make([]models.Record, 0)
			}
		default:
			if time.Since(lastTime) > 1*time.Second && len(loggers) > 0 {
				LoggerToDb(loggers)
				i = 0
				lastTime = time.Now()
				loggers = make([]models.Record, 0)
			} else {
				time.Sleep(10 * time.Microsecond)
			}
		}
	}
}

// 日志入库
func LoggerToDb(loggers []models.Record) {
	if len(loggers) == 0 {
		return
	}

	for i := 0; i < len(loggers); i += 1 {
		if len(loggers[i].Params) > 255 {
			loggers[i].Params = loggers[i].Params[0:255]
		}
		if len(loggers[i].UserAgent) > 255 {
			loggers[i].UserAgent = loggers[i].UserAgent[0:255]
		}
	}

	conn := orm.NewOrm()
	_, err := conn.InsertMulti(len(loggers), loggers)
	if err != nil {
		logger.Error("日志入库发生错误：", err)
	}
}
